import { AnswerVO } from './../vo/Answervo';
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { UserVO } from '../vo/UserVO';
import { ApiUrl } from '../api/ApiUrl';
import { ToastController, Events } from '@ionic/angular';
import { ImgService } from '../api/imgservice';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
  userItem: UserVO;
  curl: string;
  constructor(public toastController: ToastController,
    private imageService: ImgService, private router: Router,
    private cdr: ChangeDetectorRef,
    private events: Events) { }

  ngOnInit() {
    this.curl = 'assets/image/head.png';
    if (ApiUrl.user != null) {
      this.userItem = ApiUrl.user;
      // 初始化用户头像
      if (null != this.userItem.cportrait && this.userItem.cportrait.length > 0) {
        this.curl = ApiUrl.headUrl + this.userItem.cportrait + '?time=' + new Date().getTime();
      }
    } else {
      this.userItem = null;
    }
  }

  // 修改头像
  toChangeHead() {
    this.imageService.upload = {
      url: ApiUrl.toChangeHead,           // 接收图片的url
      fileKey: 'image',  // 接收图片时的key
      headers: {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' // 不加入 发生错误！！
      },
      params: { 'userid': this.userItem.iid },        // 需要额外上传的参数
      success: (data) => {
        // 加上时间防止缓存
        this.curl = ApiUrl.headUrl + ((<AnswerVO>data).data).toString() + '?time=' + new Date().getTime();
        ApiUrl.user.cportrait = ((<AnswerVO>data).data).toString();
        this.cdr.markForCheck();
        this.cdr.detectChanges();
        // this.presentToast(this.curl);
      }, // 图片上传成功后的回调
      error: (err) => { },   // 图片上传失败后的回调
      listen: () => { }   // 监听上传过程
    };
    this.imageService.showPicActionSheet();
  }
  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }
  logout() {
    ApiUrl.user = null;
    ApiUrl.txflag = false;
     // 发布事件
     this.events.publish('userlogin:change', false, Date.now());
    this.presentToast('退出成功');
    this.router.navigate(['/tabs']);
  }
}
